package actions;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import java.util.*;

import entities.*;

import javax.ejb.Local;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import utils.*;
import beans.*;

public class SearchAction extends ActionSupport {

	private String keyword, searchType;
	
	@EJB
	private SearchManager searchManager = new SearchBean();
	private ArrayList<User> resultList = null;
	private ArrayList<Item> resultItems = null;

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	public SearchManager getSearchManager() {
		return searchManager;
	}

	public void setSearchManager(SearchManager searchManager) {
		this.searchManager = searchManager;
	}

	public ArrayList<User> getResultList() {
		return resultList;
	}

	public void setResultList(ArrayList<User> resultList) {
		this.resultList = resultList;
	}

	public List<Item> getResultItems() {
		return resultItems;
	}

	public void setResultItems(ArrayList<Item> resultItems) {
		this.resultItems = resultItems;
	}

	@SuppressWarnings("unchecked")
	public String execute() {

		Map session = ActionContext.getContext().getSession();
		Integer id = (Integer) session.get("userId");

		// Get search results
		if ( searchType == null ) {
			this.addActionError("Select a search type using the radio buttons below");
			return "null";
		}
		if ( keyword == null ) {
			this.addActionError("Enter a search term");
			return "null";
		}

		// Add error on login page stating search has to be done after login
		if ( id == null && searchType.equalsIgnoreCase("people"))
			return ERROR;
		else if ( id == null && searchType != null ) {
			resultItems = (ArrayList<Item>)searchManager.directSearch(keyword,searchType,id);			
			return "general";
		}
		
		if ( searchType.equalsIgnoreCase("people") ) {
			resultList = (ArrayList<User>)searchManager.directSearch(keyword,searchType,id);			
		}
		else {
			resultItems = (ArrayList<Item>)searchManager.directSearch(keyword,searchType,id);
		}

		if ( resultList == null && resultItems == null )
			return "noresult";
		
		return searchType;
	}

}